package com.ljf.common.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljf.common.exception.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 对象转换工具类
 *
 * @author LJF
 * @since 2024-01-26
 */
public class BeanConversionUtil {

	private BeanConversionUtil() {

	}

	/**
	 * 实体类转换
	 *
	 * @param dtoEntity
	 * @param doClass
	 * @return
	 * @throws ServiceException
	 */
	public static <Do,Dto> Do conversionObj(Dto dtoEntity, Class<Do> doClass) throws ServiceException {
		// 判断dto是否为空!
		if (dtoEntity == null) {
			return null;
		}
		// 判断DoClass 是否为空
		if (doClass == null) {
			return null;
		}
		return copyNewObject(dtoEntity, doClass);
	}

	/**
	 * 集合转换
	 *
	 * @param dtoList
	 * @param doClass
	 * @return
	 * @throws ServiceException
	 */
	public static <Do,Dto> List<Do> conversionList(List<Dto> dtoList, Class<Do> doClass) throws ServiceException {
		// 判断dto是否为空!
		if (dtoList == null) {
			return Collections.emptyList();
		}
		// 判断DoClass 是否为空
		if (doClass == null) {
			return Collections.emptyList();
		}
		List<Do> list = new ArrayList<>();
		if(!CollectionUtils.isEmpty(dtoList)) {
			for (Dto dto : dtoList) {
				list.add(copyNewObject(dto, doClass));
			}
		}
		return list;
	}

	/**
	 * Page转换
	 *
	 * @param dtoPage
	 * @param doClass
	 * @return
	 * @param <Do>
	 * @param <Dto>
	 * @throws ServiceException
	 */
	public static <Do,Dto> Page<Do> conversionPage(Page<Dto> dtoPage, Class<Do> doClass) throws ServiceException {
		// 判断dto是否为空!
		if (dtoPage == null) {
			return null;
		}
		// 判断DoClass 是否为空
		if (doClass == null) {
			return null;
		}
		Page<Do> page = new Page<>();
		BeanUtils.copyProperties(dtoPage, page);
		List<Do> list = new ArrayList<>();
		if(!CollectionUtils.isEmpty(dtoPage.getRecords())) {
			for (Dto dto : dtoPage.getRecords()) {
				list.add(copyNewObject(dto, doClass));
			}
		}
		page.setRecords(list);
		return page;
	}

	/**
	 * 复制新的对象
	 *
	 * @param dto
	 * @param doClass
	 * @return
	 * @throws ServiceException
	 */
	private static <Do, Dto> Do copyNewObject(Dto dto, Class<Do> doClass) throws ServiceException {
		Do newInstance;
		try {
			newInstance = doClass.newInstance();
			BeanUtils.copyProperties(dto, newInstance);
		}
		catch (IllegalAccessException e) {
			throw new ServiceException("对象转换异常:无法处理无法访问的实体");
		}
		catch (InstantiationException e) {
			throw new ServiceException("对象转换异常:无法处理实例化");
		}
		catch (Exception e){
			throw new ServiceException("对象转换异常:无法处理未知的异常");
		}
		return newInstance;
	}

}
